package com.go.service.base.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.commons.lang3.StringUtils;

import com.go.service.base.IBaseService;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.TableMapping;

/**
 * 基础逻辑层实现类
 * @author lyb
 *
 * @param <T> model
 * @param <K> 主键
 */
public class BaseServiceImpl<T,K> implements IBaseService<T, K>{

	@SuppressWarnings("rawtypes")
	private Class<? extends Model > clazz;
	@SuppressWarnings("rawtypes")
	private Model<? extends Model> model;
	
	@SuppressWarnings("unchecked")
	public BaseServiceImpl(){
		Type genType = getClass().getGenericSuperclass();  
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        clazz = (Class<Model<?>>) params[0];
        try {
			model = clazz.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据主键获取数据
	 * @author lyb
	 */
	@SuppressWarnings("unchecked")
	public T findById(K id) {
		return (T) model.findById(id);
	}
	/**
	 * 获取符合条件的第一条数据
	 * @author lyb
	 */
	@SuppressWarnings("unchecked")
	public T findFirst(String sql) {
		return (T) model.findFirst(sql);
	}
	/**
	 * 根据主键物理删除
	 * @author lyb
	 */
	public boolean deleteById(K id) {
		return model.deleteById(id);
	}

	/**
	 * 根据主键物理删除  多个
	 * @author lyb
	 */
	public boolean deleteById(@SuppressWarnings("unchecked") K... idValues) {		
		return model.deleteById(idValues);
	}

	/**
	 * 根据id修改状态(status)值
	 * @author lyb
	 */
	public int updateStatus(Object status,K id) {
		String tableName = TableMapping.me().getTable(clazz).getName();
		String sql = " update "+ tableName +" set status = " +status +" where id = " +id;
		try {
			return Db.update(sql);
		} catch (Exception e) {  //修改报错的情况下，返回0
			e.printStackTrace();
			return 0;
		}
		
	}
	/**
	 * 单表分页查询数据(不带查询条件)
	 * @author lyb
	 * @param pageNumber   第几页
	 * @param pageSize     每页几条记录
	 * @param orderColoum  排序的字段(不排序填null)
	 * @param desc         是否倒序
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page<T> paginate(int pageNumber, int pageSize, String orderColoum,boolean desc) {
		String tableName = TableMapping.me().getTable(clazz).getName();
		String selectSql = " select * ";
		String fromSql = " from "+tableName;
		if(StringUtils.isNoneBlank(orderColoum)){
			fromSql += " order by "+orderColoum + (desc?" desc ":" ");
		}
		return (Page<T>) Db.paginate(pageNumber, pageSize, selectSql, fromSql);
	}
}
